//
//  JQFYSettingController.m
//  JQFY
//
//  Created by 代辉 on 2017/8/25.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYSettingController.h"
#import "PPAlertController.h"
#import <TZImagePickerController/TZImagePickerController.h>

@interface JQFYSettingController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,weak) UIImageView *navBGView;
@property (nonatomic,weak) UIButton *iconBtn;
@property (nonatomic,weak) UITextField *nameTextFiled;
@property (nonatomic,weak) UIImageView *top;
@property (nonatomic,weak) UILabel *clearLabel;
@property (nonatomic,strong) NSData *iconData;

@end

@implementation JQFYSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUNDCOLOR;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self setupNAV];
    [self setupUI];
    
}

- (void)setupNAV {
    
    self.title = @"设置";
    
    UIImageView *navBGView = [UIImageView new];
    self.navBGView = navBGView;
    navBGView.contentMode = UIViewContentModeScaleAspectFill;
    navBGView.image = [UIImage imageNamed:@"frame_top@2x(1)"];
    
    [self.view addSubview:navBGView];
    [navBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(64);
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveUserInfo)];
    
}
#pragma mark - 保存个人信息 -
- (void)saveUserInfo
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.removeFromSuperViewOnHide = YES;
    if (self.nameTextFiled.text.length > 14) {
        hud.detailsLabelText = @"昵称长度不能超过14位~";
        [hud hide:YES afterDelay:1];
        return;
    }
    if (self.nameTextFiled.text.length == 0) {
        self.nameTextFiled.text = self.nameTextFiled.placeholder;
        [[NSUserDefaults standardUserDefaults] setObject:self.nameTextFiled.text forKey:@"nickName"];
    }
    if (self.iconData == nil) {
        self.iconData = UIImagePNGRepresentation(self.iconBtn.currentBackgroundImage);
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:self.iconData forKey:@"iconData"];
    NSDictionary *dict = @{
                           @"token":[JQFYUserData userDataInSandbox].token,
                           @"nickname":self.nameTextFiled.text
                           };


//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.removeFromSuperViewOnHide = YES; 

    [[AFHTTPSessionManager manager] POST:@"http://app.uninhibited.cn/api/user/adduser"
                              parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                                  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                                  formatter.dateFormat = @"yyyyMMddHHmmss";
                                  NSString *str = [formatter stringFromDate:[NSDate date]];
                                  NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                                  [formData appendPartWithFileData:self.iconData name:@"head" fileName:fileName mimeType:@"image/png"];
                              }
                                progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                    if ([responseObject[@"status"] isEqualToString:@"error"]) {
                                        hud.detailsLabelText = @"上传失败";
                                    } else {
                                        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isSave"];
                                        hud.detailsLabelText = @"上传成功";
                                        if ([self.delegate respondsToSelector:@selector(settingVCChnageName:andName:icon:)]) {
                                            
                                            [self.delegate settingVCChnageName:self andName:self.nameTextFiled.text icon:self.iconImage];
                                        }
                                        
                                    }
                                    
                                    [hud hide:YES afterDelay:1];
                                    
                                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                    if (error) {
                                        hud.detailsLabelText = @"上传失败";
                                        [hud hide:YES afterDelay:1];
                                    }
                                }];
    
}
- (void)setupUI
{
    UIImageView *top = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"组1（合并）"]];
    [self.view insertSubview:top belowSubview:self.navBGView];
    [top mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.navBGView.mas_bottom);
    }];
    self.top = top;
    
    // 头像按钮
    UIButton *iconBtn = [[UIButton alloc] init];
    [self.view addSubview:iconBtn];
    iconBtn.layer.cornerRadius = 5 *SCAL;
    iconBtn.layer.masksToBounds = YES;
    
    UIImage *iconImage;
    if (self.iconImage) {
        iconImage = self.iconImage;
    } else {
        iconImage = [UIImage imageNamed:@"新icon_1（合并）"];
    }
    [iconBtn setBackgroundImage:iconImage forState:UIControlStateNormal];
    [iconBtn addTarget:self action:@selector(settingIcon) forControlEvents:UIControlEventTouchUpInside];
    [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-12 *SCAL);
        make.top.equalTo(self.top.mas_bottom).offset(12 *SCAL);
        make.size.mas_equalTo(CGSizeMake(94 *SCAL, 94 *SCAL));
    }];
    self.iconBtn = iconBtn;
    
    // 设置头像
    UIButton *settingIcon = [[UIButton alloc] init];
    [settingIcon setBackgroundImage:[UIImage imageNamed:@"设置头像（合并）"] forState:UIControlStateNormal];
    settingIcon.adjustsImageWhenHighlighted = NO;
    [settingIcon addTarget:self action:@selector(settingIcon) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingIcon];
    [settingIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(12 *SCAL);
        make.right.equalTo(iconBtn.mas_left).offset(-5 *SCAL);
        make.height.equalTo(iconBtn);
        make.top.equalTo(iconBtn);
    }];
    
    
    // 设置用户名
    UIImageView *nameBgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"修改昵称（合并）"]];
    [self.view addSubview:nameBgImg];
    [nameBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(iconBtn);
        make.left.equalTo(settingIcon);
        make.top.equalTo(settingIcon.mas_bottom).offset(12 *SCAL);
    }];
    
    UITextField *nameTextField = [UITextField new];
    [self.view addSubview:nameTextField];
    
    [nameTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    nameTextField.text = self.nickName;
    nameTextField.placeholder = @"UNINHIBITED";
    nameTextField.delegate = self;
    nameTextField.textAlignment = NSTextAlignmentCenter;
    nameTextField.font = [UIFont systemFontOfSize:17];
    nameTextField.textColor = [UIColor whiteColor];
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nameBgImg.mas_centerY);
        make.centerX.equalTo(nameBgImg);
        make.width.mas_equalTo(200 *SCAL);
    }];
    
    self.nameTextFiled = nameTextField;
    
    UILabel *tapChangeName = [UILabel new];
    tapChangeName.font = [UIFont systemFontOfSize:12];
    tapChangeName.text = @"点击修改昵称";
    tapChangeName.textColor = [UIColor whiteColor];
    [nameBgImg addSubview:tapChangeName];
    [tapChangeName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(nameBgImg);
        make.bottom.equalTo(nameBgImg).offset(-20 *SCAL);
    }];
    
    // 清除缓存
    UIButton *clearCache = [UIButton new];
    [self.view addSubview:clearCache];
    clearCache.adjustsImageWhenHighlighted = NO;
    [clearCache setBackgroundImage:[UIImage imageNamed:@"清除缓存（合并）"] forState:UIControlStateNormal];
    [clearCache addTarget:self action:@selector(clearCache) forControlEvents:UIControlEventTouchUpInside];
    [clearCache mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(iconBtn);
        make.left.equalTo(settingIcon);
        make.top.equalTo(nameBgImg.mas_bottom).offset(12 *SCAL);
    }];
    UIImageView *logo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"setting_logo"]];
    [self.view addSubview:logo];
    [logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30 *SCAL);
    }];
    
    UILabel *clearLabel = [UILabel new];
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    _clearLabel = clearLabel;
    float cache = [self folderSizeAtPath:cachesPath];
    clearLabel.text = [NSString stringWithFormat:@"清除缓存: (%.1fM)",cache];
    clearLabel.textColor = [UIColor whiteColor];
    clearLabel.font = [UIFont systemFontOfSize:13];
    [clearCache addSubview:clearLabel];
    [clearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(clearCache);
    }];
}

#pragma mark - settingIcon -
- (void)settingIcon
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.naviBgColor = [UIColor colorWithHex:0x694CE6];
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.cropRect = CGRectMake(0, (DH_Screen_Height - DH_Screen_Width) / 2, DH_Screen_Width, DH_Screen_Width);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSData *imageData = UIImagePNGRepresentation(photos[0]);
        self.iconData = imageData;
        self.iconImage = photos.firstObject;
        [self.iconBtn setBackgroundImage:photos[0] forState:UIControlStateNormal];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.nameTextFiled.editing) {
        [[NSUserDefaults standardUserDefaults] setObject:self.nameTextFiled.text forKey:@"nickName"];
        [self.nameTextFiled resignFirstResponder];
    }
}


#pragma mark - UITextFieldDelegate -
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.isFirstResponder) {
        
        [textField resignFirstResponder];
    }
    return YES;
}
#pragma mark - clearCache -
- (void)clearCache
{
    [PPAlertController alertWithTitle:@"提示" alertMessage:@"是否要清除缓存" buttonTitles:@[@"取消",@"确定"] alertVC:self selectButtonBlock:^(NSInteger selectIndex) {
        
        if (selectIndex == 1) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.removeFromSuperViewOnHide = YES;
            hud.mode = MBProgressHUDModeCustomView;
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
            
            NSError *error;
            NSArray *caches = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachesPath error:nil];
            for (NSString *sub in caches) {
                
                NSString *filePath = [cachesPath stringByAppendingPathComponent:sub];
                
                [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
                
                if (error) {
                    hud.detailsLabelText = @"清理失败";
                    [hud hide:YES afterDelay:1];
                }
            }
            hud.detailsLabelText = @"清理完毕";
            self.clearLabel.text = @"清除缓存: (0.0M)";
            [hud hide:YES afterDelay:1];
        }
    }];
}
// 计算单个文件
- (float)fileSizeAtPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}
- (float)folderSizeAtPath:(NSString *)path {
    NSFileManager *fileManager=[NSFileManager defaultManager];
    CGFloat folderSize = 0.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize += [[SDImageCache sharedImageCache] getSize] /1024.0/1024.0;
        return folderSize;
    }
    return 0;
}
#pragma mark - 监听键盘弹出 -
- (void)keyboardWillShow
{
    [self.top mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(-42 *SCAL);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - 监听键盘将要消失 -
- (void)keyboardWillHide
{
    [self.top mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64 *SCAL);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
}
@end

